package com.huawei.statistics.common.service.aliyun;

import com.aliyun.oss.OSSClient;
import com.huawei.statistics.common.Constant;
import com.huawei.statistics.utils.DateTimeUtilT;
import com.huawei.statistics.utils.PropertiesUtil;
import com.huawei.statistics.utils.RandCodeUtil;
import org.springframework.web.multipart.MultipartFile;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

/**
 * Created by 许湛司 on 2017/4/28.
 */
public class AliyunOSS {
    private static OSSClient client = null;
    private synchronized static void initialize() {
        if (client == null) {
            String akid= PropertiesUtil.getInstances().readProperty("aliyun_akid");
            String aksecret=PropertiesUtil.getInstances().readProperty("aliyun_aksecret");
            client = new OSSClient(Constant.OSS_ENDPOINT, akid,aksecret);
        }
    }

    /**
     * 上传文件到OSS
     *
     * @param rootPath      根目录
     * @param filename      文件名
     * @param multipartFile
     * @return
     */
    public static String uploadFile(String rootPath, String filename, MultipartFile multipartFile) {
        if (client == null)
            initialize();
        InputStream inputStream = null;
        try {
            inputStream = multipartFile.getInputStream();

        } catch (IOException e) {
            e.printStackTrace();
        }
        String sub=multipartFile.getOriginalFilename();
        String absolutePath = rootPath + "/" + filename+sub.substring(sub.lastIndexOf("."),sub.length());
        try {
            client.putObject(Constant.OSS_BUCKETNAME, absolutePath, inputStream);
        }catch (Exception e){
            return null;
        }
        return Constant.IMG_CDN_PREFIX + absolutePath;
    }

    /**
     * 复制文件到另外一个路径
     * @param path
     * @param desRoot
     * @return
     */
    public static String copyFileToOtherBucket(String path,String desRoot){
        if (client == null)
            initialize();
        String key=path.substring(Constant.IMG_CDN_PREFIX.length(),path.length());
        String desPath=desRoot+"/"+key.substring(key.lastIndexOf("/")+1);
        if (key.equals(desPath))
            return Constant.IMG_CDN_PREFIX + desPath;
        try {
            client.copyObject(Constant.OSS_BUCKETNAME,key,Constant.OSS_BUCKETNAME,desPath);
        }catch (Exception e){
            return path;
        }
        return Constant.IMG_CDN_PREFIX + desPath;
    }









}
